#encoding=utf8
import urllib2
import lang
import re
import md5
import net

def main():
  university_url = "http://s.xnimg.cn/a8298/allunivlist.js"
  university_content = net.fetch(university_url)
  if not university_content: return
  
  location_univs = []
  data = eval(university_content[university_content.find("=") + 1:])
  china = None
  for row in data:
    if row["id"] == "00":
      china = row
      break

  #value="体育教研部"
  re_dep_map = re.compile("(?i)value=['\"]([^'\"]+)[\"']")
  new_uid = 1
  if china:
    for prov in china["provs"]:
      name = lang.escape_unicode(prov["name"]).encode("utf8").strip()
      univs = []
      for univ in prov["univs"]:
        uid = univ["id"]
	uname = lang.escape_unicode(univ["name"]).encode("utf8").strip()
	deps = []

	dep_url = "http://www.renren.com/GetDep.do?id=%s&i=&t=1270704764434" % uid
	dep_content = net.fetch(dep_url)
	dep_content = dep_content.decode("utf8", "ignore")
	dep_content = lang.escape_html(dep_content).encode("utf8").replace("	","").strip()

	ps = re.findall(re_dep_map, dep_content)
	temp = {}
	for p in ps:
	  p = p.strip()
	  if temp.has_key(p): continue
	  temp[p] = 1
	  if p != "其它院系" and p != "其他院系":
            deps.append(p)
	
	univs.append((new_uid, uname, deps))
	new_uid += 1
      location_univs.append((name, univs))
  
  jsout = open("universitylib.js", "w")
  jsout.write("var _universities=[")
  started = False
  for (prov_name, univs) in location_univs:
    if started: jsout.write(",")
    else: started = True
    jsout.write("{name:\"%s\", univs:[" % prov_name)
    started0 = False
    for (uid, uname, deps) in univs:
      if started0: jsout.write(",")
      else: started0 = True
      jsout.write("[%s,\"%s\"]" % (uid, uname))
    jsout.write("]}")
  jsout.write("];")
  jsout.close()

  
  phpout = open("UniversityLib.php", "w")
  phpout.write("<?\n$_universities=array(")
  started = False
  for (prov_name, univs) in location_univs:
    if started: phpout.write(",")
    else: started = True
    phpout.write("array(\"name\"=>\"%s\", \"univs\"=>array(" % prov_name)
    started0 = False
    for (uid, uname, deps) in univs:
      if started0: phpout.write(",")
      else: started0 = True
      phpout.write("array(%s,\"%s\")" % (uid, uname))
    phpout.write("))")
  phpout.write(");")

  started = False
  phpout.write("\n\n$_university_deps=array(")
  for (prov_name, univs) in location_univs:
    for (uid, uname, deps) in univs:
      if len(deps) == 0: continue
      if started: phpout.write(",")
      else: started = True
      phpout.write("\n\t%s=>array(" % uid)
      started0 = False
      for dep_name in deps:
        if started0: phpout.write(",")
        else: started0 = True
        phpout.write("\"%s\"" % dep_name)
      phpout.write(")")
  phpout.write(");")

  phpout.close()

if __name__ == "__main__":
  main()
